The purpose of learning this course is that I would like to learn data analysis skill for the future career. Plus, this online course looks awesome!
Describe the work you have done this week and summarize your learning.
students2014 <- read.table(“http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/learning2014.txt”, sep=“,”, header=TRUE)
str(students2014)
The resource data is collected from the student self evaluation survey from course Introduction to Social Statistics, fall 2014 - in Finnish. This survey is devided into A, B, C and D parts. - Measures A and C are based on parts A and C in ASSIST (Approaches and Study Skills Inventory for Students). - Measures B (ASSIST B) are connected to the corresponding dimensions (Deep/SUrface/STrategic). - Measure D is based on SATS (Survey of Attitudes Toward Statistics). - Compared to the original 52 item ASSIST we here used a brief version (created by Primi, Chiesi et al), including 32 items.
The student2014 dataset has 7 variables, including gender, age, attitute, deep, str, surf, and points, and 166 rows. - gender: F (Female, 1), M (Male, 2) - age: age in years - attitude: Measure on the Likert scale (1-5) - deep: Measures B for deep questions - stra: Measures B for surface questions - surf: Measures B for strategic questions - points: Exam points excepted zero
ggpairs(learning2014, lower = list(combo = wrap(“facethist”, bins = 20)))
my_model2 <- lm(points ~ attitude + stra + surf, data = learning2014)
summary(my_model2)
According to the plot, we can see the correlation and distribution between each variables. For example, the top three variables relative data between points are attitude, stra and surf as 0.437, 0.146 and 0.144.
plot(my_model2, which = c(1,2,5), caption = list(“Residuals vs Fitted”, “Normal Q-Q”,“Residuals vs Leverage”))
my_model2 diagnostic plots
- Residuals vs Fitted: This plot shows if residuals have non-linear patterns. In the my_model2 diagnostic plots above, it shows the linear pattern in this data.
- Normal Q-Q: This plot shows if residuals are normally distributed. In the my_model2 diagnostic plots above, it shows the data is normally distributed.
- Residuals vs Leverage: This plot helps us to find influential cases.When cases are outside of the Cook’s distance (meaning they have high Cook’s distance scores), the cases are influential to the regression results. In the my_model2 diagnostic plots above, it seems no influential outliers.
alc <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/alc.txt", sep=",", header=TRUE)
str(alc)
## 'data.frame': 382 obs. of 35 variables:
## $ school : Factor w/ 2 levels "GP","MS": 1 1 1 1 1 1 1 1 1 1 ...
## $ sex : Factor w/ 2 levels "F","M": 1 1 1 1 1 2 2 1 2 2 ...
## $ age : int 18 17 15 15 16 16 16 17 15 15 ...
## $ address : Factor w/ 2 levels "R","U": 2 2 2 2 2 2 2 2 2 2 ...
## $ famsize : Factor w/ 2 levels "GT3","LE3": 1 1 2 1 1 2 2 1 2 1 ...
## $ Pstatus : Factor w/ 2 levels "A","T": 1 2 2 2 2 2 2 1 1 2 ...
## $ Medu : int 4 1 1 4 3 4 2 4 3 3 ...
## $ Fedu : int 4 1 1 2 3 3 2 4 2 4 ...
## $ Mjob : Factor w/ 5 levels "at_home","health",..: 1 1 1 2 3 4 3 3 4 3 ...
## $ Fjob : Factor w/ 5 levels "at_home","health",..: 5 3 3 4 3 3 3 5 3 3 ...
## $ reason : Factor w/ 4 levels "course","home",..: 1 1 3 2 2 4 2 2 2 2 ...
## $ nursery : Factor w/ 2 levels "no","yes": 2 1 2 2 2 2 2 2 2 2 ...
## $ internet : Factor w/ 2 levels "no","yes": 1 2 2 2 1 2 2 1 2 2 ...
## $ guardian : Factor w/ 3 levels "father","mother",..: 2 1 2 2 1 2 2 2 2 2 ...
## $ traveltime: int 2 1 1 1 1 1 1 2 1 1 ...
## $ studytime : int 2 2 2 3 2 2 2 2 2 2 ...
## $ failures : int 0 0 3 0 0 0 0 0 0 0 ...
## $ schoolsup : Factor w/ 2 levels "no","yes": 2 1 2 1 1 1 1 2 1 1 ...
## $ famsup : Factor w/ 2 levels "no","yes": 1 2 1 2 2 2 1 2 2 2 ...
## $ paid : Factor w/ 2 levels "no","yes": 1 1 2 2 2 2 1 1 2 2 ...
## $ activities: Factor w/ 2 levels "no","yes": 1 1 1 2 1 2 1 1 1 2 ...
## $ higher : Factor w/ 2 levels "no","yes": 2 2 2 2 2 2 2 2 2 2 ...
## $ romantic : Factor w/ 2 levels "no","yes": 1 1 1 2 1 1 1 1 1 1 ...
## $ famrel : int 4 5 4 3 4 5 4 4 4 5 ...
## $ freetime : int 3 3 3 2 3 4 4 1 2 5 ...
## $ goout : int 4 3 2 2 2 2 4 4 2 1 ...
## $ Dalc : int 1 1 2 1 1 1 1 1 1 1 ...
## $ Walc : int 1 1 3 1 2 2 1 1 1 1 ...
## $ health : int 3 3 3 5 5 5 3 1 1 5 ...
## $ absences : int 6 4 10 2 4 10 0 6 0 0 ...
## $ G1 : int 5 5 7 15 6 15 12 6 16 14 ...
## $ G2 : int 6 5 8 14 10 15 12 5 18 15 ...
## $ G3 : int 6 6 10 15 10 15 11 6 19 15 ...
## $ alc_use : num 1 1 2.5 1 1.5 1.5 1 1 1 1 ...
## $ high_use : logi FALSE FALSE TRUE FALSE FALSE FALSE ...
The dataset alc includes 35 varibles with 382 rows. The alc_use is the average of column Dalc and Walc (weekday and weekend alcohol consumption). If the average alcohol consumption is higher than 2, it is regarded as high alcohol usage student which is shown in column ‘high_use’ as TRUE.
Personally, I think alcohol consumption is related to a person’s relationship with family members, higher alcohol concumption may caused by bad relationship, so I select #24 famrel as one onf the analysis target. In addition, in my opinion, if a student tends to have a promising future, he/she may focus on study more rather than be absent in class too often, so I select #14 studytime and #30 absences as the interesing variables. Last, I am interested in if the score is related to alcohol consumption, so I choose #32 G3 as the fourth variable.
- #14 studytime - weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours)
- #24 famrel - quality of family relationships (numeric: from 1 - very bad to 5 - excellent)
- #30 absences - number of school absences (numeric: from 0 to 93)
- #32 G3 - final grade (numeric: from 0 to 20, output target)
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
alc_4 <- alc %>% select(16, 24, 30, 33, 34, 35)
head(alc_4, n=10)
## studytime famrel absences G3 alc_use high_use
## 1 2 4 6 6 1.0 FALSE
## 2 2 5 4 6 1.0 FALSE
## 3 2 4 10 10 2.5 TRUE
## 4 3 3 2 15 1.0 FALSE
## 5 2 4 4 10 1.5 FALSE
## 6 2 5 10 15 1.5 FALSE
## 7 2 4 0 11 1.0 FALSE
## 8 2 4 6 6 1.0 FALSE
## 9 2 4 0 19 1.0 FALSE
## 10 2 5 0 15 1.0 FALSE
high_use vs studytime
alc_4.v1 <- table(alc$high_use, alc$studytime)
round(prop.table(alc_4.v1,1), 2)
##
## 1 2 3 4
## FALSE 0.22 0.49 0.20 0.09
## TRUE 0.38 0.51 0.07 0.04
high_use vs famrel
alc_4.v2 <- table(alc$high_use, alc$famrel)
round(prop.table(alc_4.v2,1), 2)
##
## 1 2 3 4 5
## FALSE 0.03 0.03 0.15 0.49 0.31
## TRUE 0.02 0.08 0.23 0.46 0.21
high_use vs absences
alc_4.v3 <- table(alc$high_use, alc$absences)
round(prop.table(alc_4.v3,1), 2)
##
## 0 1 2 3 4 5 6 7 8 9 10 11 12 13
## FALSE 0.35 0.01 0.20 0.01 0.13 0.01 0.07 0.02 0.05 0.01 0.04 0.00 0.02 0.00
## TRUE 0.20 0.01 0.12 0.04 0.13 0.00 0.10 0.02 0.07 0.00 0.04 0.01 0.04 0.03
##
## 14 15 16 17 18 19 20 21 22 23 24 25 26 28
## FALSE 0.03 0.00 0.01 0.00 0.01 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
## TRUE 0.04 0.02 0.04 0.01 0.02 0.01 0.01 0.00 0.03 0.00 0.01 0.00 0.00 0.01
##
## 30 54 56 75
## FALSE 0.00 0.00 0.00 0.00
## TRUE 0.01 0.01 0.01 0.00
high_use vs G3
alc_4.v4 <- table(alc$high_use, alc$G3)
round(prop.table(alc_4.v4,1), 2)
##
## 0 4 5 6 7 8 9 10 11 12 13 14 15 16
## FALSE 0.12 0.00 0.01 0.05 0.02 0.06 0.07 0.13 0.11 0.07 0.05 0.09 0.10 0.05
## TRUE 0.05 0.01 0.04 0.02 0.02 0.14 0.08 0.20 0.11 0.10 0.11 0.03 0.04 0.04
##
## 17 18 19 20
## FALSE 0.01 0.04 0.02 0.00
## TRUE 0.02 0.02 0.00 0.00
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
##
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
##
## nasa
library(dplyr)
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
head(Boston, n=15)
## crim zn indus chas nox rm age dis rad tax ptratio black
## 1 0.00632 18.0 2.31 0 0.538 6.575 65.2 4.0900 1 296 15.3 396.90
## 2 0.02731 0.0 7.07 0 0.469 6.421 78.9 4.9671 2 242 17.8 396.90
## 3 0.02729 0.0 7.07 0 0.469 7.185 61.1 4.9671 2 242 17.8 392.83
## 4 0.03237 0.0 2.18 0 0.458 6.998 45.8 6.0622 3 222 18.7 394.63
## 5 0.06905 0.0 2.18 0 0.458 7.147 54.2 6.0622 3 222 18.7 396.90
## 6 0.02985 0.0 2.18 0 0.458 6.430 58.7 6.0622 3 222 18.7 394.12
## 7 0.08829 12.5 7.87 0 0.524 6.012 66.6 5.5605 5 311 15.2 395.60
## 8 0.14455 12.5 7.87 0 0.524 6.172 96.1 5.9505 5 311 15.2 396.90
## 9 0.21124 12.5 7.87 0 0.524 5.631 100.0 6.0821 5 311 15.2 386.63
## 10 0.17004 12.5 7.87 0 0.524 6.004 85.9 6.5921 5 311 15.2 386.71
## 11 0.22489 12.5 7.87 0 0.524 6.377 94.3 6.3467 5 311 15.2 392.52
## 12 0.11747 12.5 7.87 0 0.524 6.009 82.9 6.2267 5 311 15.2 396.90
## 13 0.09378 12.5 7.87 0 0.524 5.889 39.0 5.4509 5 311 15.2 390.50
## 14 0.62976 0.0 8.14 0 0.538 5.949 61.8 4.7075 4 307 21.0 396.90
## 15 0.63796 0.0 8.14 0 0.538 6.096 84.5 4.4619 4 307 21.0 380.02
## lstat medv
## 1 4.98 24.0
## 2 9.14 21.6
## 3 4.03 34.7
## 4 2.94 33.4
## 5 5.33 36.2
## 6 5.21 28.7
## 7 12.43 22.9
## 8 19.15 27.1
## 9 29.93 16.5
## 10 17.10 18.9
## 11 20.45 15.0
## 12 13.27 18.9
## 13 15.71 21.7
## 14 8.26 20.4
## 15 10.26 18.2
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
The Boston dataset is aiming to see the housing values in suburbs of Boston which includes 14 variables and 506 rows and it contains the following columns:
- crim: per capita crime rate by town.
- zn: proportion of residential land zoned for lots over 25,000 sq.ft.
- indus: proportion of non-retail business acres per town.
- chas: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).
- nox: nitrogen oxides concentration (parts per 10 million).
- rm: average number of rooms per dwelling.
- age: proportion of owner-occupied units built prior to 1940.
- dis: weighted mean of distances to five Boston employment centres.
- rad: index of accessibility to radial highways.
- tax: full-value property-tax rate per $10,000.
- ptratio: pupil-teacher ratio by town.
- black: 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town.
- lstat: lower status of the population (percent).
- medv: median value of owner-occupied homes in $1000s.
Check the correlations between variables via correlation matrix plot.
## corrplot 0.84 loaded
If the relationship between two variables are more related, the circle would be more bigger and darker. According to the size and color of the circles, we can observe that those variables are related as following:
- crim: rad, tax
- zn: dis, age, indus
- indus: nox, dis, tax
- chas: N/A
- nox: age, dis, tax
- rm: latat, medv
- age: dis, lstat
- dis: rad, tax, lstat
- rad: tax
- tax: lstat
- ptratio: medv
- black: crim, rad, tax…
- lstat: rm, age…
- medv: rm
Summary Boston dataset
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
## crim zn indus chas nox rm age
## 1 -0.4193669 0.2845483 -1.2866362 -0.2723291 -0.1440749 0.4132629 -0.1198948
## 2 -0.4169267 -0.4872402 -0.5927944 -0.2723291 -0.7395304 0.1940824 0.3668034
## 3 -0.4169290 -0.4872402 -0.5927944 -0.2723291 -0.7395304 1.2814456 -0.2655490
## 4 -0.4163384 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.0152978 -0.8090878
## 5 -0.4120741 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.2273620 -0.5106743
## 6 -0.4166314 -0.4872402 -1.3055857 -0.2723291 -0.8344581 0.2068916 -0.3508100
## dis rad tax ptratio black lstat medv
## 1 0.140075 -0.9818712 -0.6659492 -1.4575580 0.4406159 -1.0744990 0.1595278
## 2 0.556609 -0.8670245 -0.9863534 -0.3027945 0.4406159 -0.4919525 -0.1014239
## 3 0.556609 -0.8670245 -0.9863534 -0.3027945 0.3960351 -1.2075324 1.3229375
## 4 1.076671 -0.7521778 -1.1050216 0.1129203 0.4157514 -1.3601708 1.1815886
## 5 1.076671 -0.7521778 -1.1050216 0.1129203 0.4406159 -1.0254866 1.4860323
## 6 1.076671 -0.7521778 -1.1050216 0.1129203 0.4101651 -1.0422909 0.6705582
## crim zn indus chas
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563 Min. :-0.2723
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668 1st Qu.:-0.2723
## Median :-0.390280 Median :-0.48724 Median :-0.2109 Median :-0.2723
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150 3rd Qu.:-0.2723
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202 Max. : 3.6648
## nox rm age dis
## Min. :-1.4644 Min. :-3.8764 Min. :-2.3331 Min. :-1.2658
## 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366 1st Qu.:-0.8049
## Median :-0.1441 Median :-0.1084 Median : 0.3171 Median :-0.2790
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059 3rd Qu.: 0.6617
## Max. : 2.7296 Max. : 3.5515 Max. : 1.1164 Max. : 3.9566
## rad tax ptratio black
## Min. :-0.9819 Min. :-1.3127 Min. :-2.7047 Min. :-3.9033
## 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876 1st Qu.: 0.2049
## Median :-0.5225 Median :-0.4642 Median : 0.2746 Median : 0.3808
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058 3rd Qu.: 0.4332
## Max. : 1.6596 Max. : 1.7964 Max. : 1.6372 Max. : 0.4406
## lstat medv
## Min. :-1.5296 Min. :-1.9063
## 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 3.5453 Max. : 2.9865
p.s. Use the quantiles as the break points in the categorical variable
# class of the boston_scaled object
class(Boston_scale)
## [1] "matrix"
Boston_scale <- as.data.frame(Boston_scale)
# create a quantile vector of crim and print it
bins <- quantile(Boston_scale$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
# create a categorical variable 'crime'
crime <- cut(Boston_scale$crim, breaks = bins, include.lowest = TRUE)
table(crime)
## crime
## [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## 127 126 126 127
# remove original crim from the dataset
Boston_scale <- dplyr::select(Boston_scale, -crim)
# add the new categorical value to scaled data
Boston_scale <- data.frame(Boston_scale, crime)
# number of rows in the Boston dataset
n <- nrow(Boston_scale)
# choose randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# create train set
train <- Boston_scale[ind,]
# create test set
test <- Boston_scale[-ind,]
# save the correct classes from test data
correct_classes <- Boston_scale[-ind,]$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)
# linear discriminant analysis
lda.fit <- lda(crime~., data = train)
# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## 0.2425743 0.2549505 0.2500000 0.2524752
##
## Group means:
## zn indus chas nox rm
## [-0.419,-0.411] 0.9134859 -0.9547529 -0.11163110 -0.8857260 0.49951479
## (-0.411,-0.39] -0.1354812 -0.2659975 0.03346513 -0.5390344 -0.13981488
## (-0.39,0.00739] -0.3751653 0.1404473 0.19544522 0.3820860 0.08344934
## (0.00739,9.92] -0.4872402 1.0171096 -0.04073494 1.0573273 -0.38833393
## age dis rad tax ptratio
## [-0.419,-0.411] -0.9090665 0.9070415 -0.6806916 -0.7205608 -0.50452461
## (-0.411,-0.39] -0.2322999 0.3019723 -0.5581649 -0.4782114 -0.04986767
## (-0.39,0.00739] 0.3870986 -0.3633148 -0.4155974 -0.3223988 -0.21132809
## (0.00739,9.92] 0.7959295 -0.8468977 1.6382099 1.5141140 0.78087177
## black lstat medv
## [-0.419,-0.411] 0.3811662 -0.79038469 0.56659914
## (-0.411,-0.39] 0.3215448 -0.06730597 -0.03090784
## (-0.39,0.00739] 0.1334424 0.04947071 0.15016195
## (0.00739,9.92] -0.7752612 0.78519599 -0.60467269
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.08819665 0.620800068 -0.70591199
## indus 0.06840022 -0.403149961 0.38993361
## chas -0.09223249 -0.039471392 0.15198282
## nox 0.38123255 -0.643130902 -1.64359046
## rm -0.12984083 -0.039942269 -0.21137306
## age 0.23326968 -0.346804625 0.09901270
## dis -0.06730368 -0.145919048 0.01320882
## rad 3.22920796 0.711497892 0.14413484
## tax -0.11715278 0.408218760 0.33770048
## ptratio 0.13251973 -0.087849750 -0.28849944
## black -0.13310652 -0.008882632 0.09290940
## lstat 0.21014497 -0.225322446 0.33073416
## medv 0.20622701 -0.293993202 -0.26464166
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9470 0.0396 0.0134
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
# plot the lda results
plot(lda.fit, dimen = 2)
lda.arrows(lda.fit, myscale = 1)
# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
## [-0.419,-0.411] 16 11 2 0
## (-0.411,-0.39] 8 13 2 0
## (-0.39,0.00739] 0 5 19 1
## (0.00739,9.92] 0 0 0 25
library(MASS)
data('Boston')
# scale the dataset
bs <- scale(Boston)
bs <- as.data.frame(bs)
# distance measure 1: euclidean distance matrix
dist_eu <- dist(bs, method = "euclidean")
# look at the summary of the distances
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
# distance measure 2: manhattan distance matrix
dist_man <- dist(bs, method = "manhattan")
# look at the summary of the distances
summary(dist_man)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.2662 8.4832 12.6090 13.5488 17.7568 48.8618
# k-means clustering
# plot the Boston dataset with clusters
km <-kmeans(bs, centers = 4)
pairs(bs[6:10], col = km$cluster)
# k-means clustering
km <-kmeans(bs, centers = 3)
pairs(bs[6:10], col = km$cluster)
# k-means clustering
km <-kmeans(bs, centers = 2)
pairs(bs[6:10], col = km$cluster)
# k-means clustering
km <-kmeans(bs, centers = 1)
pairs(bs[6:10], col = km$cluster)
As shown in the k-means graph above (from center=4 to 1), the pair graph with center=2 seems the most resonable seperation. In the graph when center=3, some cluster are ambiguous winthin one group.
Boston_scale_original <- scale(Boston)
Boston_scale_original <- as.data.frame(Boston_scale_original)
# k-means clustering
km_original <-kmeans(Boston_scale_original, centers = 4)
pairs(Boston_scale_original[6:10], col = km_original$cluster)
# k-means clustering
km_original <-kmeans(Boston_scale_original, centers = 3)
pairs(Boston_scale_original[6:10], col = km_original$cluster)
Interpret the results. Which variables are the most influencial linear separators for the clusters? (0-2 points to compensate any loss of points from the above exercises)
Run the code below for the (scaled) train data that you used to fit the LDA. The code creates a matrix product, which is a projection of the data points.
(0-3 points) Describe and interpret the outputs, commenting on the distributions of the variables and the relationships between them.
human_ <- read.csv(file = "data/human.csv", sep = ",", header = TRUE)
# Access GGally
library(GGally)
# visualize the 'human_' variables
ggpairs(human_,
title="human data", # title of the plot
colour = "sex") # aesthetics, ggplot2 style
## Warning in warn_if_args_exist(list(...)): Extra arguments: 'colour' are being
## ignored. If these are meant to be aesthetics, submit them using the 'mapping'
## variable within ggpairs with ggplot2::aes or ggplot2::aes_string.
# compute the correlation matrix and visualize it with corrplot
cor(human_)
## Edu2.FM Labo.FM Life.Exp Edu.Exp GNI
## Edu2.FM 1.000000000 0.009564039 0.5760299 0.59325156 0.43030485
## Labo.FM 0.009564039 1.000000000 -0.1400125 0.04732183 -0.02173971
## Life.Exp 0.576029853 -0.140012504 1.0000000 0.78943917 0.62666411
## Edu.Exp 0.593251562 0.047321827 0.7894392 1.00000000 0.62433940
## GNI 0.430304846 -0.021739705 0.6266641 0.62433940 1.00000000
## Mat.Mor -0.660931770 0.240461075 -0.8571684 -0.73570257 -0.49516234
## Ado.Birth -0.529418415 0.120158862 -0.7291774 -0.70356489 -0.55656208
## Parli.F 0.078635285 0.250232608 0.1700863 0.20608156 0.08920818
## Mat.Mor Ado.Birth Parli.F
## Edu2.FM -0.6609318 -0.5294184 0.07863528
## Labo.FM 0.2404611 0.1201589 0.25023261
## Life.Exp -0.8571684 -0.7291774 0.17008631
## Edu.Exp -0.7357026 -0.7035649 0.20608156
## GNI -0.4951623 -0.5565621 0.08920818
## Mat.Mor 1.0000000 0.7586615 -0.08944000
## Ado.Birth 0.7586615 1.0000000 -0.07087810
## Parli.F -0.0894400 -0.0708781 1.00000000
This Human dataset contains the information about Human Development Index (HDI) which includes Edu2.FM (Female education index), Labo.FM (Female labour market index), Life.Exp (Life expectancy index), Edu.Exp (Education epectancy index), GNI (Gross national income), Mat.Mor (Maternal mortality ratio), Ado.Birth (Adolescent birth rate) and Parli.F (Female shares of parliamentary seats) as the dataset variables.
HDI has three dimentions, including Long and healthy life, Knowledge and A decent standard of living which are able to be evaluated by life expentanct index, education index and GNI index.
According to the human data distribution plot, we can see the correlation between Life.Exp, Edu.Exp and GNI are highly related (> 0.6)
(0-2 points) - Perform PCA on the not standardized human data. Show the variability captured by the principal components. - Draw a biplot displaying the observations by the first two principal components (PC1 coordinate in x-axis, PC2 coordinate in y-axis), along with arrows representing the original variables.
# perform principal component analysis on the not standardized human data
pca_human <- prcomp(human_)
pca_human
## Standard deviations (1, .., p=8):
## [1] 1.854416e+04 1.855219e+02 2.518701e+01 1.145441e+01 3.766241e+00
## [6] 1.565912e+00 1.912052e-01 1.591112e-01
##
## Rotation (n x k) = (8 x 8):
## PC1 PC2 PC3 PC4 PC5
## Edu2.FM -5.607472e-06 0.0006713951 -3.412027e-05 -2.736326e-04 -0.0022935252
## Labo.FM 2.331945e-07 -0.0002819357 5.302884e-04 -4.692578e-03 0.0022190154
## Life.Exp -2.815823e-04 0.0283150248 1.294971e-02 -6.752684e-02 0.9865644425
## Edu.Exp -9.562910e-05 0.0075529759 1.427664e-02 -3.313505e-02 0.1431180282
## GNI -9.999832e-01 -0.0057723054 -5.156742e-04 4.932889e-05 -0.0001135863
## Mat.Mor 5.655734e-03 -0.9916320120 1.260302e-01 -6.100534e-03 0.0266373214
## Ado.Birth 1.233961e-03 -0.1255502723 -9.918113e-01 5.301595e-03 0.0188618600
## Parli.F -5.526460e-05 0.0032317269 -7.398331e-03 -9.971232e-01 -0.0716401914
## PC6 PC7 PC8
## Edu2.FM 2.180183e-02 6.998623e-01 7.139410e-01
## Labo.FM 3.264423e-02 7.132267e-01 -7.001533e-01
## Life.Exp -1.453515e-01 5.380452e-03 2.281723e-03
## Edu.Exp 9.882477e-01 -3.826887e-02 7.776451e-03
## GNI -2.711698e-05 -8.075191e-07 -1.176762e-06
## Mat.Mor 1.695203e-03 1.355518e-04 8.371934e-04
## Ado.Birth 1.273198e-02 -8.641234e-05 -1.707885e-04
## Parli.F -2.309896e-02 -2.642548e-03 2.680113e-03
# draw a biplot of the principal component representation and the original variables
biplot(pca_human, choices = 1:2)
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
According to the biplot, the GNI tends to PC2 dimension and others variables tend to PC1 dimension.
(0-4 points) - Standardize the variables in the human data and repeat the above analysis. Interpret the results of both analysis (with and without standardizing). - Are the results different? Why or why not? Include captions (brief descriptions) in your plots where you describe the results by using not just your variable names, but the actual phenomenons they relate to.
# standardize the variables
human_std <- scale(human_)
# print out summaries of the standardized variables
summary(human_std)
## Edu2.FM Labo.FM Life.Exp Edu.Exp
## Min. :-2.8189 Min. :-2.6247 Min. :-2.7188 Min. :-2.7378
## 1st Qu.:-0.5233 1st Qu.:-0.5484 1st Qu.:-0.6425 1st Qu.:-0.6782
## Median : 0.3503 Median : 0.2316 Median : 0.3056 Median : 0.1140
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5958 3rd Qu.: 0.7350 3rd Qu.: 0.6717 3rd Qu.: 0.7126
## Max. : 2.6646 Max. : 1.6632 Max. : 1.4218 Max. : 2.4730
## GNI Mat.Mor Ado.Birth Parli.F
## Min. :-0.9193 Min. :-0.6992 Min. :-1.1325 Min. :-1.8203
## 1st Qu.:-0.7243 1st Qu.:-0.6496 1st Qu.:-0.8394 1st Qu.:-0.7409
## Median :-0.3013 Median :-0.4726 Median :-0.3298 Median :-0.1403
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.3712 3rd Qu.: 0.1932 3rd Qu.: 0.6030 3rd Qu.: 0.6127
## Max. : 5.6890 Max. : 4.4899 Max. : 3.8344 Max. : 3.1850
# perform principal component analysis (with the SVD method)
pca_human_std <- prcomp(human_std)
# draw a biplot of the principal component representation and the original variables
biplot(pca_human_std, choices = 1:2)
According to the biplot with standardized data, the Edu2.FM (Female education index), Life.Exp (Life expectancy index), Edu.Exp (Education epectancy index) and GNI (Gross national income) are related and tend to PC2 dimension. Comparing to the non-standardized data, the biplot with standardized data is more clearer to interpret the correlation between the several variables.
(0-2 points) Give your personal interpretations of the first two principal component dimensions based on the biplot drawn after PCA on the standardized human data.
After the dimension reduction by PCA, we can see the better cluster in biplot. In the first plot, we can only see the dimension tendency of index GNI is different from others. However, in the second plot, we see the indeies are devided into three parts.
(0-4 points) - Load the tea dataset from the package Factominer. Explore the data briefly: look at the structure and the dimensions of the data and visualize it. - Do Multiple Correspondence Analysis on the tea data (or to a certain columns of the data, it’s up to you). - Interpret the results of the MCA and draw at least the variable biplot of the analysis. You can also explore other plotting options for MCA. Comment on the output of the plots.
# load packages
require(FactoMineR)
## Loading required package: FactoMineR
require(ggplot2)
require(dplyr)
require(tidyr)
## Loading required package: tidyr
##
## Attaching package: 'tidyr'
## The following object is masked from 'package:magrittr':
##
## extract
library("FactoMineR")
# load data tea
data(tea)
# column names to keep in the dataset
#keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch")
# select the 'keep_columns' to create a new dataset
tea_time <- tea[, c(13, 14, 16, 15, 4, 17)]
# look at the summaries and structure of the data
summary(tea_time)
## Tea How how sugar
## black : 74 alone:195 tea bag :170 No.sugar:155
## Earl Grey:193 lemon: 33 tea bag+unpackaged: 94 sugar :145
## green : 33 milk : 63 unpackaged : 36
## other: 9
## lunch where
## lunch : 44 chain store :192
## Not.lunch:256 chain store+tea shop: 78
## tea shop : 30
##
str(tea_time)
## 'data.frame': 300 obs. of 6 variables:
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ sugar: Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ lunch: Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
## $ where: Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
#visualize the tea data
gather(tea_time) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
## Warning: attributes are not identical across measure variables;
## they will be dropped
# multiple correspondence analysis
mca <- MCA(tea_time, graph = FALSE)
# summary of the model
summary(mca)
##
## Call:
## MCA(X = tea_time, graph = FALSE)
##
##
## Eigenvalues
## Dim.1 Dim.2 Dim.3 Dim.4 Dim.5 Dim.6 Dim.7
## Variance 0.279 0.261 0.219 0.189 0.177 0.156 0.144
## % of var. 15.238 14.232 11.964 10.333 9.667 8.519 7.841
## Cumulative % of var. 15.238 29.471 41.435 51.768 61.434 69.953 77.794
## Dim.8 Dim.9 Dim.10 Dim.11
## Variance 0.141 0.117 0.087 0.062
## % of var. 7.705 6.392 4.724 3.385
## Cumulative % of var. 85.500 91.891 96.615 100.000
##
## Individuals (the 10 first)
## Dim.1 ctr cos2 Dim.2 ctr cos2 Dim.3
## 1 | -0.298 0.106 0.086 | -0.328 0.137 0.105 | -0.327
## 2 | -0.237 0.067 0.036 | -0.136 0.024 0.012 | -0.695
## 3 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 4 | -0.530 0.335 0.460 | -0.318 0.129 0.166 | 0.211
## 5 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 6 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 7 | -0.369 0.162 0.231 | -0.300 0.115 0.153 | -0.202
## 8 | -0.237 0.067 0.036 | -0.136 0.024 0.012 | -0.695
## 9 | 0.143 0.024 0.012 | 0.871 0.969 0.435 | -0.067
## 10 | 0.476 0.271 0.140 | 0.687 0.604 0.291 | -0.650
## ctr cos2
## 1 0.163 0.104 |
## 2 0.735 0.314 |
## 3 0.062 0.069 |
## 4 0.068 0.073 |
## 5 0.062 0.069 |
## 6 0.062 0.069 |
## 7 0.062 0.069 |
## 8 0.735 0.314 |
## 9 0.007 0.003 |
## 10 0.643 0.261 |
##
## Categories (the 10 first)
## Dim.1 ctr cos2 v.test Dim.2 ctr cos2
## black | 0.473 3.288 0.073 4.677 | 0.094 0.139 0.003
## Earl Grey | -0.264 2.680 0.126 -6.137 | 0.123 0.626 0.027
## green | 0.486 1.547 0.029 2.952 | -0.933 6.111 0.107
## alone | -0.018 0.012 0.001 -0.418 | -0.262 2.841 0.127
## lemon | 0.669 2.938 0.055 4.068 | 0.531 1.979 0.035
## milk | -0.337 1.420 0.030 -3.002 | 0.272 0.990 0.020
## other | 0.288 0.148 0.003 0.876 | 1.820 6.347 0.102
## tea bag | -0.608 12.499 0.483 -12.023 | -0.351 4.459 0.161
## tea bag+unpackaged | 0.350 2.289 0.056 4.088 | 1.024 20.968 0.478
## unpackaged | 1.958 27.432 0.523 12.499 | -1.015 7.898 0.141
## v.test Dim.3 ctr cos2 v.test
## black 0.929 | -1.081 21.888 0.382 -10.692 |
## Earl Grey 2.867 | 0.433 9.160 0.338 10.053 |
## green -5.669 | -0.108 0.098 0.001 -0.659 |
## alone -6.164 | -0.113 0.627 0.024 -2.655 |
## lemon 3.226 | 1.329 14.771 0.218 8.081 |
## milk 2.422 | 0.013 0.003 0.000 0.116 |
## other 5.534 | -2.524 14.526 0.197 -7.676 |
## tea bag -6.941 | -0.065 0.183 0.006 -1.287 |
## tea bag+unpackaged 11.956 | 0.019 0.009 0.000 0.226 |
## unpackaged -6.482 | 0.257 0.602 0.009 1.640 |
##
## Categorical variables (eta2)
## Dim.1 Dim.2 Dim.3
## Tea | 0.126 0.108 0.410 |
## How | 0.076 0.190 0.394 |
## how | 0.708 0.522 0.010 |
## sugar | 0.065 0.001 0.336 |
## lunch | 0.000 0.064 0.111 |
## where | 0.702 0.681 0.055 |
# visualize MCA, try 4 different arguments
plot(mca)
plot(mca, invisible=c("ind"))
plot(mca, habillage = "quali")
plot(mca, invisible=c("ind"), habillage = "quali")
# variable biplot
plot(mca, axes = c(1,2), choix=c("var"))
According to the biplot above, we can see “How”, “Tea”, “lunch” and “suger” are highly related, and “where” and “how” are highly related. ***
RATS dataset is from a nutrition study conducted in three groups of rats (Crowder and Hand, 1990). The three groups were put on different diets, and each animal’s body weight (grams) was recorded repeatedly (approximately weekly, except in week7 when two recordings were taken) over a 9-week period. The question of most interest is whether the growth profiles of the three groups differ.
BPRS (Brief Psychiatric Rating Scale) dataset is measured before treatment began (week 0) and then at weekly intervals for eight weeks. The BPRS assesses the level of 18 symptom constructs such as hostility, suspiciousness, hallucinations and grandiosity; each of these is rated from one (not present) to seven (extremely severe). The scale is used to evaluate patients suspected of having schizophrenia.
RATS dataset is from a nutrition study conducted in three groups of rats (Crowder and Hand, 1990). The three groups were put on different diets, and each animal’s body weight (grams) was recorded repeatedly (approximately weekly, except in week7 when two recordings were taken) over a 9-week period. The question of most interest is whether the growth profiles of the three groups differ.
RATS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/rats.txt", header = T)
# variables' names
names(RATS)
## [1] "ID" "Group" "WD1" "WD8" "WD15" "WD22" "WD29" "WD36" "WD43"
## [10] "WD44" "WD50" "WD57" "WD64"
# RATS dataset structure
str(RATS)
## 'data.frame': 16 obs. of 13 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Group: int 1 1 1 1 1 1 1 1 2 2 ...
## $ WD1 : int 240 225 245 260 255 260 275 245 410 405 ...
## $ WD8 : int 250 230 250 255 260 265 275 255 415 420 ...
## $ WD15 : int 255 230 250 255 255 270 260 260 425 430 ...
## $ WD22 : int 260 232 255 265 270 275 270 268 428 440 ...
## $ WD29 : int 262 240 262 265 270 275 273 270 438 448 ...
## $ WD36 : int 258 240 265 268 273 277 274 265 443 460 ...
## $ WD43 : int 266 243 267 270 274 278 276 265 442 458 ...
## $ WD44 : int 266 244 267 272 273 278 271 267 446 464 ...
## $ WD50 : int 265 238 264 274 276 284 282 273 456 475 ...
## $ WD57 : int 272 247 268 273 278 279 281 274 468 484 ...
## $ WD64 : int 278 245 269 275 280 281 284 278 478 496 ...
# RATS dataset summary
summary(RATS)
## ID Group WD1 WD8 WD15
## Min. : 1.00 Min. :1.00 Min. :225.0 Min. :230.0 Min. :230.0
## 1st Qu.: 4.75 1st Qu.:1.00 1st Qu.:252.5 1st Qu.:255.0 1st Qu.:255.0
## Median : 8.50 Median :1.50 Median :340.0 Median :345.0 Median :347.5
## Mean : 8.50 Mean :1.75 Mean :365.9 Mean :369.1 Mean :372.5
## 3rd Qu.:12.25 3rd Qu.:2.25 3rd Qu.:480.0 3rd Qu.:476.2 3rd Qu.:486.2
## Max. :16.00 Max. :3.00 Max. :555.0 Max. :560.0 Max. :565.0
## WD22 WD29 WD36 WD43
## Min. :232.0 Min. :240.0 Min. :240.0 Min. :243.0
## 1st Qu.:267.2 1st Qu.:268.8 1st Qu.:267.2 1st Qu.:269.2
## Median :351.5 Median :356.5 Median :360.0 Median :360.0
## Mean :379.2 Mean :383.9 Mean :387.0 Mean :386.0
## 3rd Qu.:492.5 3rd Qu.:497.8 3rd Qu.:504.2 3rd Qu.:501.0
## Max. :580.0 Max. :590.0 Max. :597.0 Max. :595.0
## WD44 WD50 WD57 WD64
## Min. :244.0 Min. :238.0 Min. :247.0 Min. :245.0
## 1st Qu.:270.0 1st Qu.:273.8 1st Qu.:273.8 1st Qu.:278.0
## Median :362.0 Median :370.0 Median :373.5 Median :378.0
## Mean :388.3 Mean :394.6 Mean :398.6 Mean :404.1
## 3rd Qu.:510.5 3rd Qu.:516.0 3rd Qu.:524.5 3rd Qu.:530.8
## Max. :595.0 Max. :612.0 Max. :618.0 Max. :628.0
Since the attribite of ID and Group are categorical variables, we can change the type of the dataset from integer to factor by factor() function!
library(dplyr) # Access the packages dplyr and tidyr
library(tidyr)
RATS$ID <- factor(RATS$ID) # Factor ID & Group
RATS$Group <- factor(RATS$Group)
In order to visulaize the data, we would like to convert the original wide-form to long-form first.
RATSL <- RATS %>% gather(key = WD, value = rats_weight, -ID, -Group) # Convert to long-form
RATSL <- RATSL %>% mutate(Time = as.integer(substr(WD, 3, 4))) # Extract the week number, from the 3th letter to the 4 th letter
glimpse(RATSL)
## Observations: 176
## Variables: 5
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1,…
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, …
## $ WD <chr> "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "…
## $ rats_weight <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 445, 55…
## $ Time <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8, …
Let’s implement ggplot to visualize the RATSL dataset by line chart.
library(ggplot2)
ggplot(RATSL, aes(x = ID, y = rats_weight, color = Group, group = Time)) +
geom_point() +
geom_line() +
scale_color_brewer(palette = 'Dark2') +
theme_classic(base_size = 12)
ggplot(RATSL, aes(x = Time, y = rats_weight, color = Group, group = ID)) +
geom_point() +
geom_line() +
scale_color_brewer(palette = 'Dark2') +
theme_classic(base_size = 12)
In the above plots, we can see the growth pattern from the first measurement to the last measurement is quite similar. However, we need to do further analysis to see whether the growth profiles of the three groups differ.
So we would like to check the growth pattern for each group by ANOVA analysis. In the begining, we plot a boxplot to see the rough data distribution in the dataset for each group.
# Box plots
# ++++++++++++++++++++
# Plot weight by group and color by group
library(ggpubr)
ggboxplot(RATSL, x = "Group", y = "rats_weight",
color = "Group", palette = c("#00AFBB", "#E7B800", "#FC4E07"),
order = c("1", "2", "3"),
ylab = "rats_weight", xlab = "Group")
And then, we would like to seperate each group’s data from the original RATSL dataset.
library(tidyverse)
## ── Attaching packages ────────────────────────────────────────────────────────────────────────────────── tidyverse 1.3.0 ──
## ✔ tibble 2.1.3 ✔ stringr 1.4.0
## ✔ readr 1.3.1 ✔ forcats 0.4.0
## ✔ purrr 0.3.3
## ── Conflicts ───────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ tidyr::extract() masks magrittr::extract()
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ✖ MASS::select() masks dplyr::select()
## ✖ purrr::set_names() masks magrittr::set_names()
RATSL_1 <- RATSL %>% filter(Group==1)
RATSL_2 <- RATSL %>% filter(Group==2)
RATSL_3 <- RATSL %>% filter(Group==3)
Now, we can standardized the rats_weight in RATSL dataset and conduct ANOVA anaysis to see the relationship between rat’s weight and the time. We assume that H0 is when rats’ weight is not related to the time and H1 is when rats’ weight is related to the time.
library(standardize)
# Standardize rats_weight of RATSL_1 dataset
RATSL_1$rats_weight <- scale(RATSL_1$rats_weight)
# Standardize rats_weight of RATSL_2 dataset
RATSL_2$rats_weight <- scale(RATSL_2$rats_weight)
# Standardize rats_weight of RATSL_3 dataset
RATSL_3$rats_weight <- scale(RATSL_3$rats_weight)
# Compute the analysis of variance
RATSL_1_aov <- aov(rats_weight ~ Time, data = RATSL_1)
RATSL_2_aov <- aov(rats_weight ~ Time, data = RATSL_2)
RATSL_3_aov <- aov(rats_weight ~ Time, data = RATSL_3)
# Summary of the analysis
summary(RATSL_1_aov)
## Df Sum Sq Mean Sq F value Pr(>F)
## Time 1 22.99 22.990 30.89 3.01e-07 ***
## Residuals 86 64.01 0.744
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
summary(RATSL_2_aov)
## Df Sum Sq Mean Sq F value Pr(>F)
## Time 1 3.63 3.633 3.876 0.0556 .
## Residuals 42 39.37 0.937
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
summary(RATSL_3_aov)
## Df Sum Sq Mean Sq F value Pr(>F)
## Time 1 12.08 12.076 16.4 0.000216 ***
## Residuals 42 30.92 0.736
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
par(mfrow=c(2,2))
plot(RATSL_1_aov)
plot(RATSL_2_aov)
plot(RATSL_3_aov)
According to the ANOVA analysis report, ……
In addtion, in ANOVA analysis Normal Q-Q plot of group 2, the dots are not well distributed on the line, which suggests that it is a bimodal distribution for the original data distribution.
BPRS (Brief Psychiatric Rating Scale) dataset is measured before treatment began (week 0) and then at weekly intervals for eight weeks. The BPRS assesses the level of 18 symptom constructs such as hostility, suspiciousness, hallucinations and grandiosity; each of these is rated from one (not present) to seven (extremely severe). The scale is used to evaluate patients suspected of having schizophrenia.
BPRS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/BPRS.txt", header = T)
# variables' names
names(BPRS)
## [1] "treatment" "subject" "week0" "week1" "week2" "week3"
## [7] "week4" "week5" "week6" "week7" "week8"
# RATS dataset structure
str(BPRS)
## 'data.frame': 40 obs. of 11 variables:
## $ treatment: int 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : int 1 2 3 4 5 6 7 8 9 10 ...
## $ week0 : int 42 58 54 55 72 48 71 30 41 57 ...
## $ week1 : int 36 68 55 77 75 43 61 36 43 51 ...
## $ week2 : int 36 61 41 49 72 41 47 38 39 51 ...
## $ week3 : int 43 55 38 54 65 38 30 38 35 55 ...
## $ week4 : int 41 43 43 56 50 36 27 31 28 53 ...
## $ week5 : int 40 34 28 50 39 29 40 26 22 43 ...
## $ week6 : int 38 28 29 47 32 33 30 26 20 43 ...
## $ week7 : int 47 28 25 42 38 27 31 25 23 39 ...
## $ week8 : int 51 28 24 46 32 25 31 24 21 32 ...
# RATS dataset summary
summary(BPRS)
## treatment subject week0 week1 week2
## Min. :1.0 Min. : 1.00 Min. :24.00 Min. :23.00 Min. :26.0
## 1st Qu.:1.0 1st Qu.: 5.75 1st Qu.:38.00 1st Qu.:35.00 1st Qu.:32.0
## Median :1.5 Median :10.50 Median :46.00 Median :41.00 Median :38.0
## Mean :1.5 Mean :10.50 Mean :48.00 Mean :46.33 Mean :41.7
## 3rd Qu.:2.0 3rd Qu.:15.25 3rd Qu.:58.25 3rd Qu.:54.25 3rd Qu.:49.0
## Max. :2.0 Max. :20.00 Max. :78.00 Max. :95.00 Max. :75.0
## week3 week4 week5 week6 week7
## Min. :24.00 Min. :20.00 Min. :20.00 Min. :19.00 Min. :18.0
## 1st Qu.:29.75 1st Qu.:28.00 1st Qu.:26.00 1st Qu.:22.75 1st Qu.:23.0
## Median :36.50 Median :34.50 Median :30.50 Median :28.50 Median :30.0
## Mean :39.15 Mean :36.35 Mean :32.55 Mean :31.23 Mean :32.2
## 3rd Qu.:44.50 3rd Qu.:43.00 3rd Qu.:38.00 3rd Qu.:37.00 3rd Qu.:38.0
## Max. :76.00 Max. :66.00 Max. :64.00 Max. :64.00 Max. :62.0
## week8
## Min. :20.00
## 1st Qu.:22.75
## Median :28.00
## Mean :31.43
## 3rd Qu.:35.25
## Max. :75.00
Since the attribite of treatment and subject are categorical variables, we can change the type of the dataset from integer to factor by factor() function!
library(dplyr) # Access the packages dplyr and tidyr
library(tidyr)
BPRS$treatment <- factor(BPRS$treatment) # Factor treatment & subject
BPRS$subject <- factor(BPRS$subject)
str(BPRS)
## 'data.frame': 40 obs. of 11 variables:
## $ treatment: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : Factor w/ 20 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ week0 : int 42 58 54 55 72 48 71 30 41 57 ...
## $ week1 : int 36 68 55 77 75 43 61 36 43 51 ...
## $ week2 : int 36 61 41 49 72 41 47 38 39 51 ...
## $ week3 : int 43 55 38 54 65 38 30 38 35 55 ...
## $ week4 : int 41 43 43 56 50 36 27 31 28 53 ...
## $ week5 : int 40 34 28 50 39 29 40 26 22 43 ...
## $ week6 : int 38 28 29 47 32 33 30 26 20 43 ...
## $ week7 : int 47 28 25 42 38 27 31 25 23 39 ...
## $ week8 : int 51 28 24 46 32 25 31 24 21 32 ...
In order to visulaize the data, we would like to convert the original wide-form to long-form first.
BPRSL <- BPRS %>% gather(key = week, value = scale, -treatment, -subject) # Convert to long-form
BPRSL <- BPRSL %>% mutate(Week = as.integer(substr(week, 5, 5))) # Extract the week number, from the 5th letter to the 5 th letter
glimpse(BPRSL)
## Observations: 360
## Variables: 5
## $ treatment <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
## $ subject <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, …
## $ week <chr> "week0", "week0", "week0", "week0", "week0", "week0", "week…
## $ scale <int> 42, 58, 54, 55, 72, 48, 71, 30, 41, 57, 30, 55, 36, 38, 66,…
## $ Week <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,…
Since the “Week” variable also belongs to categorical data, we can use factor() function to factorize it!
BPRSL$Week <- factor(BPRSL$Week)
glimpse(BPRSL)
## Observations: 360
## Variables: 5
## $ treatment <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,…
## $ subject <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, …
## $ week <chr> "week0", "week0", "week0", "week0", "week0", "week0", "week…
## $ scale <int> 42, 58, 54, 55, 72, 48, 71, 30, 41, 57, 30, 55, 36, 38, 66,…
## $ Week <fct> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,…
Let’s visualize the BPRSL dataset by ox chart.
attach(BPRSL)
plot(subject, scale, main="Boxplot of BPRS dataset: Scale vs. Subject",
xlab="Subject ", ylab="Scale ", pch=19)
In the above boxplot, we can see the scale result of 8-week-treatment for each subject. We can clearly see the 1st, 19th and 20th subjects has some abnormally high scale during the observation which may suggest that the patients’ condition is not quite stable, so they perhaps need further therapy or observation.
attach(BPRSL)
## The following objects are masked from BPRSL (pos = 3):
##
## scale, subject, treatment, week, Week
plot(treatment, scale, main="Boxplot of BPRS dataset: Scale vs. Treatment",
xlab="Treatment ", ylab="Scale ", pch=19)
In the above boxchart, the two treatment implemented in this observation seems has not so much differences. Both means are around but less than 40 and the treatment no.2 is a bit less than treatment no.1.
attach(BPRSL)
## The following objects are masked from BPRSL (pos = 3):
##
## scale, subject, treatment, week, Week
## The following objects are masked from BPRSL (pos = 4):
##
## scale, subject, treatment, week, Week
plot(Week, scale, main="Boxplot of BPRS dataset: Scale vs. Week",
xlab="Week ", ylab="Scale ", pch=19)
In the above boxchart, it is quite clear to see the patients’ average scales are decreasing along the time (week).
According to the boxplots above, we know that the average patients’ condition are getting better through the series of treatments. ***